package net.example.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import net.example.manager.ClientGlobalCache;
import net.example.manager.GGApplication;
import net.example.model.CommunicateType;
import net.example.model.ContractType;
import net.example.model.contract.MediaCommunicateContract;
import net.example.model.event.NotReadMsgCountChangedEvent;
import net.example.model.event.RequestEvent;
import net.example.activity.fragment.GroupFragment;
import net.example.activity.fragment.FriendFragment;
import net.example.activity.fragment.SessionFragment;
import net.example.activity.fragment.SettingsFragment;
import net.example.manager.Manager;
import net.example.model.CommunicateMediaType;
import net.example.model.event.UnitRequestCountChangedEvent;
import net.example.ggtalk.R;
import net.example.utils.CommonHelper;
import net.example.utils.CommonOptions;
import net.example.utils.ConfigUtils;
import net.example.utils.IntentUtils;
import net.example.activity.view.SystemBarTintManager;
import net.example.utils.ToastUtils;
import net.example.utils.android.AndroidUtil;

import com.oraycn.esbasic.helpers.StringHelper;
import com.oraycn.esbasic.objectManagement.cache.HotCache;
import com.oraycn.esframework.core.ClientType;
import com.oraycn.omcs.MultimediaDeviceType;
import com.oraycn.omcs.MultimediaManagerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;


public class MainActivity extends FragmentActivity {
    private HashMap<Integer, Button> mTabs;
    private SettingsFragment settingFragment;
    private SessionFragment sessionFragment;
    private GroupFragment groupFragment;
    private FriendFragment friendFragment;
    private Fragment[] fragments;
    public boolean isConflict = false;
    private boolean isCurrentAccountRemoved = false;
    public static List<String> staticFacesList;
    private TextView tv_friend_request_count;
    private TextView tv_group_request_count;
    private TextView tv_unread_msg_count;

    /**
     * 检查当前用户是否被删除
     */
    public boolean getCurrentAccountRemoved() {
        return isCurrentAccountRemoved;
    }

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            // 检测版本更新
            initStaticFaces();
            setContentView(R.layout.activity_main);
            initView();
            initFragment();
            initSystemBar();
            setSystemBar();
            //Picasso.get().setIndicatorsEnabled(true);//开启加载图片的指示器
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
            ClientGlobalCache.getInstance().initNotReadMsgMap();
        } catch (Exception ex) {
            ToastUtils.showLongTemp(this,ex.getMessage());
            ex.printStackTrace();
        }
        mHandler = new Handler();

    }

    private boolean isFirstLoad=true;//是否为第一次加载
    @Override
    protected void onStart() {
        super.onStart();
        if(isFirstLoad)
        {
            //第一次加载获取会话页面是否有聊天记录，没有则跳转到好友界面
            if(sessionFragment.getMessageItemCount()==0){
                View view=new View(MainActivity.this);
                view.setId(R.id.btn_friend_list);
                this.onTabClicked(view);
            }
            isFirstLoad=false;
        }
        Log.i("MainActivity","进入前台");
        //Manager.getInstance().isInHisBlackList("aa01");//进入到前台时任意发送一条消息给服务端，若掉线尽快触发掉线重连
    }

    private void initFragment() {
        settingFragment = new SettingsFragment();
        groupFragment = new GroupFragment();
        sessionFragment = new SessionFragment();
        friendFragment = new FriendFragment();
        fragments = new Fragment[]{
                friendFragment,
                groupFragment,
                sessionFragment,
                settingFragment};
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, friendFragment)
                .add(R.id.fragment_container, groupFragment)
                .add(R.id.fragment_container, sessionFragment)
                .add(R.id.fragment_container, settingFragment)
                .hide(friendFragment)
                .hide(groupFragment)
                .hide(sessionFragment)
                .hide(settingFragment);

             fragmentTransaction.show(sessionFragment).commit();
    }


    @SuppressLint("NewApi")
    private void setSystemBar() {
        int size = getStatusBarHeight();
    }

    private void initStaticFaces() {
        try {
            staticFacesList = new ArrayList<String>();
            String[] faces = getAssets().list("face/png");
            for (int i = 0; i < faces.length; i++) {
                staticFacesList.add(faces[i]);
            }
            // 去掉删除图片
            staticFacesList.remove("emotion_del_normal.png");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 沉浸式状态栏
     */
    @SuppressLint("ResourceAsColor")
    private void initSystemBar() {
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setNavigationBarTintEnabled(true);
        tintManager.setTintColor(R.color.bar);
        int pading = getStatusBarHeight();

    }

    // 获取状态栏高度
    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height",
                "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 初始化组件
     */
    public void initView() {
        this.setTabMsgCount();
        mTabs = new HashMap<>();
        mTabs.put(R.id.btn_friend_list, (Button) findViewById(R.id.btn_friend_list));
        mTabs.put(R.id.btn_contactGroup, (Button) findViewById(R.id.btn_contactGroup));
        mTabs.put(R.id.btn_conversation, (Button) findViewById(R.id.btn_conversation));
        mTabs.put(R.id.btn_main_setting, (Button) findViewById(R.id.btn_main_setting));
        mTabs.get(R.id.btn_conversation).setSelected(true);
//        this.setTabMsgCount();
        // int requestAddFriendCount = ClientGlobalCache.getInstance().getRequestAddFriendCount();

    }

    /**
     * 设置菜单栏的消息数量
     * */
    private void setTabMsgCount()
    {
        this.tv_friend_request_count = (TextView) findViewById(R.id.friend_request_count);
        this.tv_group_request_count = (TextView) findViewById(R.id.group_request_count);
        this.tv_unread_msg_count = (TextView) findViewById(R.id.unread_msg_count);
        ///TO DO 设置缓存中的未读 数量。  现在默认为刚登录的账号未读数量为0
    }


    /**
     * button点击事件
     *
     * @param view
     */
    public void onTabClicked(View view) {
        FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < fragments.length; i++) {
            trx.hide(fragments[i]);
        }
        for (Map.Entry<Integer,Button> entry:  mTabs.entrySet())
        {
            entry.getValue().setSelected(false);
        }
        switch (view.getId()) {
            case R.id.btn_friend_list:
                mTabs.get(R.id.btn_friend_list).setSelected(true);
                trx.show(friendFragment).commit();
                break;
            case R.id.btn_contactGroup:
                mTabs.get(R.id.btn_contactGroup).setSelected(true);
                trx.show(groupFragment).commit();
                break;
            case R.id.btn_conversation:
                mTabs.get(R.id.btn_conversation).setSelected(true);
                trx.show(sessionFragment).commit();
                sessionFragment.getNewMessageItem();
                break;
            case R.id.btn_main_setting:
                mTabs.get(R.id.btn_main_setting).setSelected(true);
                trx.show(settingFragment).commit();
                break;
        }
    }

    public void back(View view) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (conflictBuilder != null) {
            conflictBuilder.create().dismiss();
            conflictBuilder = null;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }

    private boolean firstLoad=true;
    @Override
    protected void onResume() {
        super.onResume();
        if (this.firstLoad) {
            Manager.getInstance().requestMyOfflineMessage();//界面全部初始化完成后，再获取离线消息
            this.firstLoad = false;
        }
        try {
            Uri uri = (Uri) HotCache.getValue4OnceOnly(CommonOptions.MediaIntent);
            if (uri != null) {
                GGApplication.getInstance().getFileLogger().logWithTime("uri:"+uri.getQuery());
                String mediaSpeakerID = uri.getQueryParameter("MediaSpeakerID"); //多媒体消息发送者
                if (StringHelper.isNullOrEmpty(mediaSpeakerID)) {
                    GGApplication.getInstance().getFileLogger().logWithTime(String.format("mediaSpeakerID is null"));
                    return;
                }
                int communicateType = Integer.parseInt(uri.getQueryParameter("CommunicateType"));
                int communicateMediaType = Integer.parseInt(uri.getQueryParameter("CommunicateMediaType"));
                int destClientType = Integer.parseInt(uri.getQueryParameter("DestClientType"));
                int sourceClientType=Integer.parseInt(uri.getQueryParameter("SourceClientType"));
                String tag = uri.getQueryParameter("Tag");
                MediaCommunicateContract mediaCommunicateContract = new MediaCommunicateContract(CommunicateMediaType.getCommunicateMediaType(communicateMediaType), CommunicateType.getCommunicateType(communicateType), tag, destClientType);
                if (mediaCommunicateContract.getDestClientType() != -1 && mediaCommunicateContract.getDestClientType() != ClientType.ANDROID.getType()) {
                    return;
                }
                GGApplication.getInstance().postMediaCommunicateMessage(mediaSpeakerID, getContractTypeByCode(sourceClientType), ContractType.MediaCommunicate.getType(), mediaCommunicateContract);
            }
        } catch (Exception e) {
            Log.e("MainActivity", e.getMessage());
        }
    }

    private ClientType getContractTypeByCode(int code) {
        for (ClientType type : ClientType.values()) {
            if (type.getType() == code) {
                return type;
            }
        }
        return null;
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("MainActivity","进入后台");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
        }
        return super.onKeyDown(keyCode, event);
    }

    private android.app.AlertDialog.Builder conflictBuilder;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        int tabID = getIntent().getIntExtra("tabID", -1);
        if (tabID != -1) {
            View view = new View(this);
            view.setId(tabID);
            this.onTabClicked(view);
        }

    }

    private void actionNotificationMessage()
    {
        String talkingUserID=getIntent().getStringExtra("TalkingUserID");
        if(!StringHelper.isNullOrEmpty(talkingUserID))//从通知消息点击过来的
        {
            boolean isGroup=getIntent().getBooleanExtra("isGroup",false);
            if(isGroup)
            {
                IntentUtils.startActivityForString_Dubble(this, ChatActivity.class,
                        ConfigUtils.TalkingType, ConfigUtils.Group_Talking, ConfigUtils.Group_Talking, talkingUserID);
            }
            else
            {
                IntentUtils.startActivityForString_Dubble(this, ChatActivity.class,
                        ConfigUtils.TalkingType, ConfigUtils.Person_Talking, ConfigUtils.Person_Talking, talkingUserID);
            }
        }
    }

    private Handler mHandler;

    public void onEventMainThread(RequestEvent event) {
        boolean chatActivityisForeground= AndroidUtil.isForeground(this, ChatActivity.class.getName());//当前是否处于聊天页面 （因为聊天页面中MultimediaDeviceType.Microphone一直处于工作状态）

        if (event.mediaType == CommunicateMediaType.Audio) {
            //在语音、视频 请求等待或接通中 的页面，再次收到视频或语音请求，直接拒绝
            if((!chatActivityisForeground &&MultimediaManagerFactory.GetSingleton().deviceIsWorking(MultimediaDeviceType.Microphone)))
            {
                Manager.getInstance().sendMediaCommunicate(event.requestID,CommunicateMediaType.Audio,CommunicateType.Busy,"",event.clientType.getType());
                Manager.getInstance().sendSystemMessage(event.requestID, String.format("设备忙，已拒绝%s的语音聊天请求",ClientGlobalCache.getInstance().getUserName(event.requestID)),false);// 发送系统消息
                return;
            }
            IntentUtils.startActivity(this, VoiceCallActivity.class, "event", event);
        } else if (event.mediaType == CommunicateMediaType.Video) {
            //在语音、视频 请求等待或接通中 的页面，再次收到视频或语音请求，直接拒绝
            if((!chatActivityisForeground &&MultimediaManagerFactory.GetSingleton().deviceIsWorking(MultimediaDeviceType.Microphone))||MultimediaManagerFactory.GetSingleton().deviceIsWorking(MultimediaDeviceType.Camera))
            {
                Manager.getInstance().sendMediaCommunicate(event.requestID,CommunicateMediaType.Video,CommunicateType.Busy,"",event.clientType.getType());
                Manager.getInstance().sendSystemMessage(event.requestID, String.format("设备忙，已拒绝%s的视频聊天请求",ClientGlobalCache.getInstance().getUserName(event.requestID)),false);// 发送系统消息
                return;
            }
            IntentUtils.startActivity(this, VideoCallActivity.class, "event", event);
        } else if (event.mediaType == CommunicateMediaType.GroupVideo) {

            boolean videoChat4GroupActivityisForeground= AndroidUtil.isForeground(this, VideoChat4GroupActivity.class.getName());
            boolean videoCall4GroupActivityisForeground= AndroidUtil.isForeground(this, VideoCall4GroupActivity.class.getName());
            if(videoChat4GroupActivityisForeground||videoCall4GroupActivityisForeground||MultimediaManagerFactory.GetSingleton().deviceIsWorking(MultimediaDeviceType.Camera)||(!chatActivityisForeground &&MultimediaManagerFactory.GetSingleton().deviceIsWorking(MultimediaDeviceType.Microphone)))//若正在群视频请求中或被请求中，或者摄像头正在用，直接拒绝
            {
                if(!StringHelper.isNullOrEmpty(event.Tag))
                {
                    String[] tag=  event.Tag.split(ConfigUtils.ColonSeparator);
                    String videoGroupID=tag[0];
                    String groupID=tag[0].split("_")[0];
                    String[] memberIDs=tag[1].split(ConfigUtils.CommaSeparator);
                    Manager.getInstance().sendSystemMessage(groupID, String.format("设备忙，已拒绝%s的群视频聊天请求",ClientGlobalCache.getInstance().getUserName(event.requestID)),true);// 发送系统消息
                    Manager.getInstance().sendGroupVideoChat4Reject(videoGroupID,memberIDs,CommunicateType.Busy);
                }
                return;
            }
            IntentUtils.startActivity(this, VideoCall4GroupActivity.class, "event", event);
        }
        else if (event.mediaType == CommunicateMediaType.RemoteControl) {
        } else if (event.mediaType == CommunicateMediaType.RemoteDisk) {
        } else if (event.mediaType == CommunicateMediaType.RemoteHelp) {
        } else if (event.mediaType == CommunicateMediaType.Online) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Drawable drawable = getResources().getDrawable(
                            R.drawable.tab_contact_list_bg);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                            drawable.getMinimumHeight());
                    mTabs.get(R.id.btn_friend_list).setCompoundDrawables(null, drawable, null, null);
                }
            });
        } else if (event.mediaType == CommunicateMediaType.Offline) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Drawable drawable = getResources().getDrawable(
                            R.drawable.tab_contact_list_bg_off);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                            drawable.getMinimumHeight());
                    mTabs.get(R.id.btn_friend_list).setCompoundDrawables(null, drawable, null, null);
                }
            });
        }
    }

    public void onEventMainThread(UnitRequestCountChangedEvent event)
    {
//        取消底部验证消息的请求数量
//        if(event.UnitType== UnitType.User)
//        {
//            if(event.Count >0)
//            {
//                this.tv_friend_request_count.setVisibility(View.VISIBLE);
//                this.tv_friend_request_count.setText(CommonHelper.getMaxCountStr4Show(event.Count));
//            }
//            else {
//                this.tv_friend_request_count.setVisibility(View.INVISIBLE);
//            }
//        }else if(event.UnitType==UnitType.Group)
//        {
//            if(event.Count >0)
//            {
//                this.tv_group_request_count.setVisibility(View.VISIBLE);
//                this.tv_group_request_count.setText(CommonHelper.getMaxCountStr4Show(event.Count));
//            }
//            else {
//                this.tv_group_request_count.setVisibility(View.INVISIBLE);
//            }
//        }
    }

    public void onEventMainThread(NotReadMsgCountChangedEvent event)
    {
        if(event.Count==0)
        {
            this.tv_unread_msg_count.setVisibility(View.INVISIBLE);
        }else {
            this.tv_unread_msg_count.setVisibility(View.VISIBLE);
            this.tv_unread_msg_count.setText(CommonHelper.getMaxCountStr4Show(event.Count));
        }
    }

}